<template>
    <div style="height: 850px;">
        <br/>
        <p style="font-size: xx-large; margin-left: 400px;">新建房间</p>
        <br/>
        <a-form
            :model="formState"
            name="basic"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            @finish="onFinish"
            @finishFailed="onFinishFailed"
            style="width: 1300px;"
        >
            <a-form-item
                label="房间名"
                name="name"
                :rules="[{ required: true, message: '请输入房间名' }]"
            >
                <a-input v-model:value="formState.name" />
            </a-form-item>
            <a-form-item
                label="房间描述"
                name="description"
                :rules="[{ required: true, message: '请输入房间描述' }]"
            >
                <a-textarea v-model:value="formState.description" show-count />
            </a-form-item>
            <a-form-item label="标签" name="labelIds">
              <a-select
                v-model:value="labelsSelected"
                mode="multiple"
                style="width: 100%"
                placeholder="选择标签"
                :options="labelsAll"
                @change="handleLabelChange"
              >
                <template #dropdownRender="{ menuNode: menu }">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0" />
                  <a-space style="padding: 4px 8px">
                    <a-input ref="inputRef" v-model:value="newLabelName" placeholder="Please enter item" />
                    <a-button type="text" @click="newLabel">
                      <template #icon>
                        <plus-outlined />
                      </template>
                      Add item
                    </a-button>
                  </a-space>
                </template>
              </a-select>
            </a-form-item>
            <a-form-item label="房间封面" name="cover">
              <a-upload
                v-model:file-list="fileList"
                name="avatar"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :before-upload="beforeUploadCover"
                :customRequest = "handleUploadCover"
                @change="handleChangeCover"
              >
                <img v-if="formState.cover" :src="coverUrl" alt="avatar" width="100px" height="100px"/>
                <div v-else>
                  <loading-outlined v-if="loading"></loading-outlined>
                  <plus-outlined v-else></plus-outlined>
                  <div class="ant-upload-text">Upload</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                <a-button type="primary" html-type="submit">提交</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script lang="ts">
export default {
    name: 'NewRoom'
}
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive, defineComponent } from 'vue';
import { InboxOutlined, PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { UploadChangeParam, UploadProps, message } from 'ant-design-vue';
import { getLabelList, addLabel } from '@/api/label_api';
import { insertOrUpdateRoom } from '@/api/room_api';

interface FormState {
  id: number,
  name: string,
  description: string,
  labelIds: string,
  cover: any,
}
const formState = reactive<FormState>({
  id: 0,
  name: '',
  description: '',
  labelIds: '',
  cover: null
});
const fileList = ref([]);
const loading = ref<boolean>(false)
const coverUrl = ref<string>('')
const labelsAll = ref<{label: string, value: number, disabled: boolean}[]>([])
const labelsSelected = ref<string[]>([]);
const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes;
  },
});
const newLabelName = ref<string>('');
const inputRef = ref();
const props = defineProps(['id'])

onMounted(async () => {
    // 请求label下拉框数据
    await getLabelList(1)
    .then(response => {
    for (let index = 0; index < response.data.length; index++) {
        labelsAll.value.push(response.data[index])
    }
    console.log(response.data)
    })
    if (props.id != '0') {
    }
});

const onFinish = async (values: any) => { // 表单提交成功
  let formData = new FormData
  formData.append("name", formState.name)
  formData.append("description", formState.description)
  formData.append("labelIds", labelsSelected.value.toString())
  formData.append("cover", formState.cover)
  console.log(formData)
  await insertOrUpdateRoom(formData)
  .then(response => {
    message.info("新建成功")
  })
  .catch(error => {});
};

const onFinishFailed = (errorInfo: any) => { // 表单提交失败
  console.log('Failed:', errorInfo);
};

const handleLabelChange = (value: string[]) => {
};

const newLabel = async (e:any) => {
  e.preventDefault();
  if (newLabelName.value === "") {
    message.error("请填入标签名")
    return
  }
  let data = {
    "name": newLabelName.value,
    "type": 1
  }
  await addLabel(data)
  .then(response => {
    labelsAll.value.push({
      "label": newLabelName.value,
      "value": response.data,
      "disabled": false
    });
  })
  .catch(error => {
  })
  newLabelName.value = '';
  console.log(labelsAll)
  setTimeout(() => {
    inputRef.value?.focus();
  }, 0);
}

const beforeUploadCover: UploadProps['beforeUpload'] = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
  if (!isJpgOrPng) {
      message.error('You can only upload JPG file!');
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
      message.error('Image must smaller than 10MB!');
  }
  return isJpgOrPng && isLt10M;
}

const handleUploadCover = (info:any) => {
  formState.cover = info.file
  coverUrl.value = window.URL.createObjectURL(info.file)
}

const handleChangeCover = (info:UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loading.value = true
  } else if (info.file.status === 'done') {
    formState.cover = info.file
    loading.value = false
  } else {
    loading.value = false;
    message.error('upload cover error');
  }
}
</script>